package com.adulcimer.core.tools;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Simon
 * @create 2025/7/21
 * @Description redis相关工具类 （需要更改目前是chat类项目）
 **/
@Component
public class RedisChatCache {

    private final HashOperations<String, String, Map<String, Object>> hashOps;
    private static final String PREFIX = "chat:session:";

    public RedisChatCache(RedisTemplate<String, ?> redisTemplate) {
        this.hashOps = redisTemplate.opsForHash();
    }

    public void addMessage(Long sessionId, Map<String, Object> message) {
        String key = PREFIX + sessionId;
        String field = "message:" + System.currentTimeMillis();
        hashOps.put(key, field, message);
        hashOps.getOperations().expire(key, 24, TimeUnit.HOURS);
    }

    public long getMessageCount(Long sessionId) {
        String key = PREFIX + sessionId;
        return hashOps.keys(key).size();
    }

    public Map<String, Map<String, Object>> getAllMessages(Long sessionId) {
        String key = PREFIX + sessionId;
        return hashOps.entries(key);
    }

    public void clearMessages(Long sessionId) {
        String key = PREFIX + sessionId;
        hashOps.getOperations().delete(key);
    }
}
